#coding: utf-8

__author__ = 'vlasovai'

import codecs, csv, datetime, os, re, time

from django.conf import settings

from models import Roditel, Det

def convert(file, code=701, test=True):
    lst = csv.reader(open(os.path.join(settings.PROJECT_PATH, file), 'rb'), delimiter=':', quotechar='|')

    date_format = ('%d.%m.%Y', '%d.%m.%y')
    c = codecs.lookup('utf8')

    d = re.compile(ur'([\da-z]+)', re.U)

    for row in [x for x in lst][1:]:
        f, i, o, dat, psr, pnm, ind, nsp, ulc, dom, kor, kv = row

        f = c.decode(f)[0].strip().lower()
        i = c.decode(i)[0].strip().lower()
        o = c.decode(o)[0].strip().lower()

        dat = c.decode(dat)[0].strip()
        for fmt in date_format:
            try:
                dat = datetime.date.fromtimestamp(time.mktime(time.strptime(dat, fmt)))
                break
            except:
                pass

        if not isinstance(dat, datetime.date):
            raise Exception('%s %s %s: %s'%(f, i, o, dat))

        psr = c.decode(psr)[0].strip().lower()
        pnm = c.decode(pnm)[0].strip().lower()

        ind = c.decode(ind)[0].strip()

        nsp = c.decode(nsp)[0].strip()
        ulc = c.decode(ulc)[0].strip()
        dom = c.decode(dom)[0].strip()
        dom_parts = d.finditer(dom)

        __dom = list()
        for part in dom_parts:
            __dom.append(part.group())
        dom = u''.join(__dom)

        kor = c.decode(kor)[0].strip().lower()
        kv = c.decode(kv)[0].strip()
        if not test:

            rod = Roditel(f=f, i=i, o=o, dat=dat,
                    psr=psr, pnm=pnm, ind=ind, nsp=nsp,
                    ulc=ulc, dom=dom, kor=kor, kv=kv, code=code)
            rod.save(force_insert=True)

def convert_det(file, code=701, test=True):
    lst = csv.reader(open(os.path.join(settings.PROJECT_PATH, file), 'rb'), delimiter=' ', quotechar='|')

    date_format = ('%d.%m.%Y', '%d.%m.%y')
    c = codecs.lookup('utf8')

    d = re.compile(ur'([\da-z]+)', re.U)

    for row in [x for x in lst][1:]:
        try:
            if len(row) == 7:
                _a, _b, _c, f, i, o, dat  = row
                o = c.decode(o)[0].strip().lower()
            elif len(row) == 6:
                _a, _b, _c, f, i, dat  = row
                o = u''
            else:
                _a, _b, _c, f, i, o1, o2, dat  = row
                o = u'%s %s'%(c.decode(o1)[0].strip().lower(), c.decode(o2)[0].strip().lower())
        except Exception:
            print row
            raise

        f = c.decode(f)[0].strip().lower()
        i = c.decode(i)[0].strip().lower()

        if not isinstance(dat, datetime.date):
            dat = dat.strip()
            for fmt in date_format:
                try:
                    dat = datetime.date.fromtimestamp(time.mktime(time.strptime(dat, fmt)))
                    break
                except:
                    pass

        if not isinstance(dat, datetime.date):
            raise Exception('%s %s %s: %s'%(f, i, o, dat))


        if not test:
            det = Det(f=f, i=i, o=o, dat=dat, code=code)
            det.save(force_insert=True)